#include "MessageLogPanel.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDateTime>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QLabel>
#include <QCheckBox>
#include <QPushButton>
#include <QTextEdit>
#include <QScrollBar>

namespace ModbusPlexLink {

// ============================================================================
// ModbusMessageViewer 实现
// ============================================================================

ModbusMessageViewer::ModbusMessageViewer(QWidget *parent)
    : QWidget(parent)
    , m_channel(nullptr)
    , m_paused(false)
    , m_messageCount(0)
{
    setupUi();
}

void ModbusMessageViewer::setupUi() {
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(8);

    // 工具栏
    QHBoxLayout* toolbarLayout = new QHBoxLayout();
    toolbarLayout->setContentsMargins(8, 8, 8, 0);
    toolbarLayout->setSpacing(8);

    QLabel* titleLabel = new QLabel(tr("📡 Modbus报文"), this);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(10);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    toolbarLayout->addWidget(titleLabel);

    toolbarLayout->addStretch();

    m_pauseCheck = new QCheckBox(tr("暂停"), this);
    connect(m_pauseCheck, &QCheckBox::toggled,
            this, &ModbusMessageViewer::onPauseToggled);
    toolbarLayout->addWidget(m_pauseCheck);

    m_clearBtn = new QPushButton(tr("清空"), this);
    m_clearBtn->setObjectName("toolButton");
    connect(m_clearBtn, &QPushButton::clicked,
            this, &ModbusMessageViewer::onClearClicked);
    toolbarLayout->addWidget(m_clearBtn);

    m_exportBtn = new QPushButton(tr("导出"), this);
    m_exportBtn->setObjectName("toolButton");
    connect(m_exportBtn, &QPushButton::clicked,
            this, &ModbusMessageViewer::onExportClicked);
    toolbarLayout->addWidget(m_exportBtn);

    mainLayout->addLayout(toolbarLayout);

    // 报文显示区域
    m_messageDisplay = new QTextBrowser(this);
    m_messageDisplay->setObjectName("messageDisplay");
    m_messageDisplay->setOpenExternalLinks(false);
    mainLayout->addWidget(m_messageDisplay);

    // 样式
    setStyleSheet(R"(
        #messageDisplay {
            background-color: #1F2937;
            color: #F3F4F6;
            border: 1px solid #374151;
            border-radius: 6px;
            padding: 8px;
            font-family: 'Consolas', 'Courier New', monospace;
            font-size: 9pt;
        }
        #toolButton {
            background-color: white;
            border: 1px solid #E5E7EB;
            border-radius: 4px;
            padding: 4px 12px;
            color: #374151;
        }
        #toolButton:hover {
            background-color: #F3F4F6;
            border-color: #3B82F6;
        }
        QCheckBox {
            color: #374151;
        }
    )");
}

void ModbusMessageViewer::addMessage(const QString& direction, const QString& device,
                                     const QString& function, const QString& address,
                                     const QString& data, bool success) {
    if (m_paused) return;

    m_messageCount++;
    QString html = formatMessage(direction, device, function, address, data, success);
    m_messageDisplay->append(html);

    // 限制最大行数
    if (m_messageCount > 1000) {
        m_messageDisplay->clear();
        m_messageCount = 0;
    }
}

void ModbusMessageViewer::clearMessages() {
    m_messageDisplay->clear();
    m_messageCount = 0;
}

void ModbusMessageViewer::setChannel(Channel* channel) {
    m_channel = channel;
    clearMessages();
}

void ModbusMessageViewer::onClearClicked() {
    clearMessages();
}

void ModbusMessageViewer::onExportClicked() {
    QString fileName = QFileDialog::getSaveFileName(
        this,
        tr("导出报文日志"),
        QDateTime::currentDateTime().toString("messages_yyyyMMdd_hhmmss.txt"),
        tr("文本文件 (*.txt);;所有文件 (*.*)"));

    if (fileName.isEmpty()) return;

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("导出失败"),
                           tr("无法写入文件: %1").arg(fileName));
        return;
    }

    QTextStream out(&file);
    out << m_messageDisplay->toPlainText();
    file.close();

    QMessageBox::information(this, tr("导出成功"),
                           tr("报文日志已导出到: %1").arg(fileName));
}

void ModbusMessageViewer::onPauseToggled(bool paused) {
    m_paused = paused;
}

QString ModbusMessageViewer::formatMessage(const QString& direction, const QString& device,
                                          const QString& function, const QString& address,
                                          const QString& data, bool success) {
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
    QString directionIcon = (direction == "TX") ? "⬆" : "⬇";
    QString statusColor = success ? "#10B981" : "#EF4444";
    QString statusText = success ? "✓" : "✗";

    return QString(
        "<span style='color: #9CA3AF;'>%1</span> "
        "<span style='color: #60A5FA;'>%2</span> "
        "<span style='color: #F59E0B;'>%3</span> "
        "<span style='color: #EC4899;'>FC%4</span> "
        "<span style='color: #8B5CF6;'>@%5</span> "
        "<span style='color: %6;'>%7</span> "
        "<span style='color: #D1D5DB;'>%8</span>"
    ).arg(timestamp)
     .arg(directionIcon)
     .arg(device)
     .arg(function)
     .arg(address)
     .arg(statusColor)
     .arg(statusText)
     .arg(data);
}

// ============================================================================
// MessageLogPanel 实现
// ============================================================================

MessageLogPanel::MessageLogPanel(QWidget *parent)
    : QWidget(parent)
    , m_channel(nullptr)
{
    setupUi();
}

MessageLogPanel::~MessageLogPanel() {
}

void MessageLogPanel::setupUi() {
    QHBoxLayout* mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);

    // 左侧切换按钮栏
    QWidget* sideBar = new QWidget(this);
    sideBar->setObjectName("sideBar");
    sideBar->setFixedWidth(60);

    QVBoxLayout* sideLayout = new QVBoxLayout(sideBar);
    sideLayout->setContentsMargins(4, 8, 4, 8);
    sideLayout->setSpacing(4);

    m_buttonGroup = new QButtonGroup(this);

    // 报文按钮
    m_messageBtn = new QPushButton("📡\n报文", sideBar);
    m_messageBtn->setObjectName("sideButton");
    m_messageBtn->setCheckable(true);
    m_messageBtn->setChecked(true);
    m_messageBtn->setFixedHeight(60);
    m_messageBtn->setCursor(Qt::PointingHandCursor);
    connect(m_messageBtn, &QPushButton::clicked,
            this, &MessageLogPanel::onMessageModeClicked);
    m_buttonGroup->addButton(m_messageBtn, 0);
    sideLayout->addWidget(m_messageBtn);

    // 日志按钮
    m_logBtn = new QPushButton("📋\n日志", sideBar);
    m_logBtn->setObjectName("sideButton");
    m_logBtn->setCheckable(true);
    m_logBtn->setFixedHeight(60);
    m_logBtn->setCursor(Qt::PointingHandCursor);
    connect(m_logBtn, &QPushButton::clicked,
            this, &MessageLogPanel::onLogModeClicked);
    m_buttonGroup->addButton(m_logBtn, 1);
    sideLayout->addWidget(m_logBtn);

    sideLayout->addStretch();

    mainLayout->addWidget(sideBar);

    // 右侧内容区域
    m_stackedWidget = new QStackedWidget(this);

    m_messageViewer = new ModbusMessageViewer(this);
    m_stackedWidget->addWidget(m_messageViewer);

    m_logViewer = new LogViewerWidget(this);
    m_stackedWidget->addWidget(m_logViewer);

    mainLayout->addWidget(m_stackedWidget, 1);

    // 样式
    setStyleSheet(R"(
        #sideBar {
            background-color: #F3F4F6;
            border-right: 1px solid #E5E7EB;
        }
        #sideButton {
            background-color: transparent;
            border: none;
            border-radius: 6px;
            color: #6B7280;
            font-size: 9pt;
            text-align: center;
            padding: 8px;
        }
        #sideButton:hover {
            background-color: #E5E7EB;
        }
        #sideButton:checked {
            background-color: #3B82F6;
            color: white;
        }
    )");

    // 默认显示报文
    setActiveButton(m_messageBtn);
}

void MessageLogPanel::setChannel(Channel* channel) {
    m_channel = channel;

    if (m_messageViewer) {
        m_messageViewer->setChannel(channel);
    }

    // 日志查看器是全局的，不需要设置通道
}

void MessageLogPanel::onMessageModeClicked() {
    m_stackedWidget->setCurrentIndex(0);
    setActiveButton(m_messageBtn);
}

void MessageLogPanel::onLogModeClicked() {
    m_stackedWidget->setCurrentIndex(1);
    setActiveButton(m_logBtn);
}

void MessageLogPanel::setActiveButton(QPushButton* button) {
    // 样式由 checkable + checked 状态自动处理
    button->setChecked(true);
}

} // namespace ModbusPlexLink
